package com.qyhl.school.school.reporter.detail;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolReporterActBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.SCHOOL_REPORTER_ACT_DETAIL)
public class SchoolReporterActDetailActivity extends BaseActivity implements SchoolReporterActDetailContract.SchoolReporterActDetailView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.address)
    TextView address;
    @BindView(R2.id.date)
    TextView date;
    @BindView(R2.id.cover)
    RoundedImageView cover;
    @BindView(R2.id.summary)
    WebView webview;
    @BindView(R2.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.sign_btn)
    TextView signBtn;

    private int actId;

    private SchoolReporterActDetailPresenter mPresenter;

    private SchoolReporterActBean mBean;

    private String username;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_act_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        actId = getIntent().getIntExtra("actId", 0);
        mPresenter = new SchoolReporterActDetailPresenter(this);

        username = CommonUtils.getInstance().getUserName();

        mPresenter.getDetail(username, actId);

    }

    /**
     * 初始化webview
     */
    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(false);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);//是否阻塞加载网络图片  协议http or https
        settings.setUseWideViewPort(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        String htmlString = analysisContent(mBean.getContent());
        webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
        webview.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
        webview.setWebViewClient(mWebViewClient);

    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webview.measure(w, h);

        }
    };

    private String analysisContent(String content) {
        content = "<html><head></head><body>" + content + "</body></html>";
        Document doc = Jsoup.parse(content);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("style", "max-width:100% !important;max-height:auto !important");
        }
        return doc.toString();
    }


    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(username, actId);
            }
        });

    }

    @Override
    public void signResult(boolean isSuccess, String msg) {
        dismissLoading();
        showToast(msg);

        if (isSuccess) {
            signBtn.setEnabled(false);
            signBtn.setText("活动已报名");
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(SchoolReporterActBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mBean = bean;
        title.setText(mBean.getTitle());
        address.setText(mBean.getAddress());

        initWebView();//初始化webview

        if (StringUtils.isNotEmpty(mBean.getEndDate())) {
            date.setText(mBean.getStartDate() + "—" + mBean.getEndDate());
        } else {
            date.setText(mBean.getStartDate());
        }

        Glide.with(this)
                .load(mBean.getLogo())
                .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                .into(cover);

        if (mBean.isReportOver()) {
            signBtn.setEnabled(false);
            signBtn.setText("活动已结束");
        } else if (mBean.isReported()) {
            signBtn.setEnabled(false);
            signBtn.setText("活动已报名");
        } else {
            signBtn.setEnabled(true);
            signBtn.setText("立即报名");
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Error);
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }


    @OnClick({R2.id.back_btn, R2.id.sign_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.sign_btn) {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        showLoading();
                        username = CommonUtils.getInstance().getUserName();
                        mPresenter.doSign(username, mBean.getId());
                    } else {
                        showToast("尚未登录或登录已失效！");
                        RouterManager.routerLogin(SchoolReporterActDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                username = CommonUtils.getInstance().getUserName();
                mPresenter.getDetail(username, actId);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }

}
